<template>
	<el-upload
		class="avatar-uploader"
		:show-file-list="false"
		:before-upload="beforerUpload"
		:http-request="handleHttp"
	>
		<img v-if="imageUrl" :src="imageUrl" class="avatar" />
		<el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
	</el-upload>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps } from "element-plus";
import AV from "leancloud-storage";
import { useRoute } from "vue-router";
const route = useRoute();
let { query } = route;
console.log(query);

defineProps(["image"]);
const emit = defineEmits(["update:image"]);
function getBase64(img: any, callback: any) {
	const reader = new FileReader();
	reader.addEventListener("load", () => callback(reader.result));
	reader.readAsDataURL(img);
}
let imageUrl = ref<string>("");
imageUrl.value = query.poster as string;
const beforerUpload: UploadProps["beforeUpload"] = (rawFile) => {
	if (rawFile.type !== "image/jpeg") {
		ElMessage.error("请上传jpg的图片");
		return false;
	}
	return true;
};

const handleHttp = (file: any) => {
	getBase64(file.file, (base64: string) => {
		const file = new AV.File("img.jpg", { base64 });
		file.save().then((url: any) => {
			imageUrl.value = url.attributes.url;
			emit("update:image", imageUrl.value);
		});
	});
};
</script>

<style scoped>
.avatar-uploader .avatar {
	width: 178px;
	height: 178px;
	display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
	border: 1px dashed var(--el-border-color);
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
	border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	text-align: center;
}
</style>
